package com.hy.proxy.common;

import java.util.concurrent.*;

/**
 * @Author: hy
 * @Date: Created in 2019/10/9/17:23
 * @Description: 线程池
 * @Version: 1.0
 */
public enum ThreadPoolUtils {

    Instance;

    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 获取线程池单例对象
     *
     * @return
     */
    public ThreadPoolExecutor getInstance() {
        return this.threadPoolExecutor;
    }

    /**
     * 直接执行线程，不关注返回值
     *
     * @param runnable
     */
    public void executor(Runnable runnable) {
        this.threadPoolExecutor.execute(runnable);
    }

    public void shutdown() {
        this.threadPoolExecutor.shutdown();
    }

    /**
     * 初始化线程池
     */
    ThreadPoolUtils() {

        //线程池长期维持的线程数 = JVM可用的CPU数量 * 2
        int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;

        //线程数量上限
        int maximumPoolSize = corePoolSize;

        //超过 corePoolSize 数量的线程存活时常
        long keepAliveTime = 0L;
        TimeUnit timeUnit = TimeUnit.SECONDS;

        //任务排队队列
        BlockingQueue<Runnable> runnableQueue = new ArrayBlockingQueue<>(512);

        //任务队列满时，线程池对新任务的拒绝策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy();

        threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                timeUnit,
                runnableQueue,
                handler);
    }

}